#!/bin/bash

# 小智ESP32服务器 - 网络问题修复脚本
# 用于修复Ubuntu软件源连接问题

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查网络连接
check_network() {
    log_info "正在检查网络连接..."
    
    if ! ping -c 1 8.8.8.8 &> /dev/null; then
        log_error "无法连接到互联网，请检查网络设置"
        exit 1
    fi
    
    log_success "网络连接正常"
}

# 备份原始源列表
backup_sources() {
    log_info "正在备份原始软件源配置..."
    
    if [[ -f /etc/apt/sources.list ]]; then
        sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup.$(date +%Y%m%d_%H%M%S)
        log_success "已备份sources.list"
    fi
    
    if [[ -d /etc/apt/sources.list.d ]]; then
        sudo mkdir -p /etc/apt/sources.list.d/backup
        sudo cp /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/backup/ 2>/dev/null || true
        log_success "已备份sources.list.d"
    fi
}

# 更换为国内镜像源
use_chinese_mirrors() {
    log_info "正在更换为国内镜像源..."
    
    # 检测Ubuntu版本
    local ubuntu_version=$(lsb_release -cs)
    
    # 创建新的sources.list
    sudo tee /etc/apt/sources.list > /dev/null << EOF
# 清华大学镜像源
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${ubuntu_version} main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${ubuntu_version}-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${ubuntu_version}-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${ubuntu_version}-security main restricted universe multiverse

# 阿里云镜像源（备用）
# deb https://mirrors.aliyun.com/ubuntu/ ${ubuntu_version} main restricted universe multiverse
# deb https://mirrors.aliyun.com/ubuntu/ ${ubuntu_version}-updates main restricted universe multiverse
# deb https://mirrors.aliyun.com/ubuntu/ ${ubuntu_version}-backports main restricted universe multiverse
# deb https://mirrors.aliyun.com/ubuntu/ ${ubuntu_version}-security main restricted universe multiverse
EOF

    # 移除有问题的源
    sudo rm -f /etc/apt/sources.list.d/realsense*.list 2>/dev/null || true
    
    log_success "已更换为国内镜像源"
}

# 修复DNS设置
fix_dns() {
    log_info "正在修复DNS设置..."
    
    # 备份原始resolv.conf
    if [[ -f /etc/resolv.conf ]]; then
        sudo cp /etc/resolv.conf /etc/resolv.conf.backup
    fi
    
    # 使用可靠的DNS服务器
    sudo tee /etc/resolv.conf > /dev/null << EOF
# 可靠的DNS服务器
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 223.5.5.5
nameserver 223.6.6.6
EOF

    # 防止NetworkManager覆盖
    if [[ -f /etc/NetworkManager/NetworkManager.conf ]]; then
        sudo sed -i '/\[main\]/a dns=none' /etc/NetworkManager/NetworkManager.conf 2>/dev/null || true
        sudo systemctl restart NetworkManager 2>/dev/null || true
    fi
    
    log_success "DNS设置已修复"
}

# 清理APT缓存
clean_apt_cache() {
    log_info "正在清理APT缓存..."
    
    sudo apt-get clean
    sudo apt-get autoclean
    sudo apt-get autoremove -y
    sudo rm -rf /var/lib/apt/lists/*
    
    log_success "APT缓存已清理"
}

# 更新软件包列表
update_packages() {
    log_info "正在更新软件包列表..."
    
    if sudo apt-get update; then
        log_success "软件包列表更新成功"
        return 0
    else
        log_error "软件包列表更新失败"
        return 1
    fi
}

# 测试镜像源速度
test_mirror_speed() {
    log_info "正在测试镜像源速度..."
    
    echo "测试清华大学镜像源："
    time curl -s https://mirrors.tuna.tsinghua.edu.cn/ubuntu/dists/ > /dev/null && log_success "清华大学镜像源可用" || log_warning "清华大学镜像源可能不可用"
    
    echo "测试阿里云镜像源："
    time curl -s https://mirrors.aliyun.com/ubuntu/dists/ > /dev/null && log_success "阿里云镜像源可用" || log_warning "阿里云镜像源可能不可用"
}

# 显示手动配置选项
show_manual_options() {
    echo "========================================"
    echo "🛠️  手动配置选项"
    echo "========================================"
    echo ""
    echo "如果自动修复无效，您可以尝试以下手动方法："
    echo ""
    echo "1. 手动编辑软件源："
    echo "   sudo nano /etc/apt/sources.list"
    echo ""
    echo "2. 推荐的国内镜像源："
    echo "   - 清华大学：https://mirrors.tuna.tsinghua.edu.cn/ubuntu/"
    echo "   - 阿里云：https://mirrors.aliyun.com/ubuntu/"
    echo "   - 中国科技大学：https://mirrors.ustc.edu.cn/ubuntu/"
    echo ""
    echo "3. 临时使用代理："
    echo "   export http_proxy=http://your-proxy:port"
    echo "   export https_proxy=http://your-proxy:port"
    echo ""
    echo "4. 检查网络设置："
    echo "   ping 8.8.8.8"
    echo "   nslookup archive.ubuntu.com"
    echo ""
    echo "5. 如果使用的是公司网络，可能需要配置代理："
    echo "   sudo nano /etc/apt/apt.conf.d/95proxies"
    echo ""
    echo "6. 临时解决方案（使用本地缓存）："
    echo "   sudo apt-get --no-download --fix-missing install"
    echo ""
    echo "========================================"
}

# 主函数
main() {
    echo "========================================"
    echo "小智ESP32服务器 - 网络问题修复工具"
    echo "========================================"
    echo ""
    echo "🔧 此脚本将帮助您修复Ubuntu软件源连接问题"
    echo ""
    echo "⚠️  注意："
    echo "- 此脚本需要sudo权限"
    echo "- 将备份原始配置"
    echo "- 建议在中国大陆使用"
    echo "========================================"
    echo ""
    
    # 检查是否为root用户
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用sudo运行此脚本：sudo $0"
        exit 1
    fi
    
    # 检查网络
    check_network
    
    # 备份配置
    backup_sources
    
    # 修复DNS
    fix_dns
    
    # 使用国内镜像
    use_chinese_mirrors
    
    # 清理缓存
    clean_apt_cache
    
    # 更新软件包
    if update_packages; then
        log_success "网络问题修复成功！"
        echo ""
        echo "🎉 现在您可以重新运行安装脚本："
        echo "   sudo ./install_deps.sh"
    else
        log_error "网络问题修复失败，请尝试手动配置"
        show_manual_options
        exit 1
    fi
    
    # 测试镜像速度
    test_mirror_speed
    
    echo ""
    echo "========================================"
    echo "🎯 修复完成！建议重新启动系统："
    echo "   sudo reboot"
    echo "========================================"
}

# 运行主函数
main "$@"